// 智能童话书工具函数
    
    // 格式化故事文本
    function formatStoryText(text) {
        return text
            .split('\n')
            .filter(line => line.trim())
            .map(line => `<p class="story-paragraph">${line.trim()}</p>`)
            .join('');
    }
    
    // 显示错误信息
    function showError(message) {
        const loadingMessage = document.getElementById('loadingMessage');
        const storyContent = document.getElementById('storyContent');
        
        if (loadingMessage) loadingMessage.style.display = 'none';
        if (storyContent) {
            storyContent.innerHTML = `
                <div class="alert alert-danger text-center">
                    <i class="bi bi-exclamation-triangle"></i>
                    <h5>故事生成失败</h5>
                    <p>${message}</p>
                    <button class="btn btn-primary" onclick="location.reload()">
                        <i class="bi bi-arrow-clockwise"></i> 重新尝试
                    </button>
                </div>
            `;
            storyContent.style.display = 'block';
        }
    }
    
    // 更新统计信息
    async function updateStats() {
        try {
            const response = await fetch('/api/system_status');
            const stats = await response.json();
            
            const totalStoriesEl = document.getElementById('totalStories');
            const userSessionsEl = document.getElementById('userSessions');
            const averageRatingEl = document.getElementById('averageRating');
            const systemStatusEl = document.getElementById('systemStatus');
            
            if (totalStoriesEl) totalStoriesEl.textContent = stats.total_stories || 0;
            if (userSessionsEl) userSessionsEl.textContent = stats.user_sessions || 0;
            if (averageRatingEl) averageRatingEl.textContent = stats.average_rating?.toFixed(1) || '4.2';
            if (systemStatusEl) systemStatusEl.textContent = stats.system_status === '运行正常' ? '🟢' : '🟡';
            
        } catch (error) {
            console.warn('⚠️ 统计更新失败:', error);
        }
    }
    
    // 全局函数
    window.generateNewStory = function() {
        const welcomeMessage = document.getElementById('welcomeMessage');
        const storyContent = document.getElementById('storyContent');
        const loadingMessage = document.getElementById('loadingMessage');
        const storyForm = document.getElementById('storyForm');
        
        if (welcomeMessage) welcomeMessage.style.display = 'block';
        if (storyContent) storyContent.style.display = 'none';
        if (loadingMessage) loadingMessage.style.display = 'none';
        
        // 重置表单
        if (storyForm) storyForm.reset();
        
        // 滚动到表单
        if (storyForm) storyForm.scrollIntoView({ behavior: 'smooth' });
    };
    
    window.shareStory = function() {
        if (navigator.share) {
            navigator.share({
                title: '智能童话书 - 精彩故事',
                text: '我刚刚用AI生成了一个很棒的童话故事！',
                url: window.location.href
            }).catch(err => console.log('分享失败:', err));
        } else {
            // 复制到剪贴板
            const storyText = document.querySelector('.story-content-box');
            if (storyText) {
                navigator.clipboard.writeText(storyText.textContent)
                    .then(() => alert('故事已复制到剪贴板！'))
                    .catch(() => alert('复制失败，请手动选择文本复制'));
            }
        }
    };
    
    window.rateStory = function() {
        const rating = prompt('请为这个故事评分（1-5星）：');
        if (rating && rating >= 1 && rating <= 5) {
            // 发送评分到后端
            fetch('/api/rate_story', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ rating: parseInt(rating) })
            }).then(() => {
                alert('感谢您的评分！');
                updateStats();
            }).catch(() => {
                alert('评分提交失败，请稍后重试');
            });
        }
    };
    
    // 页面加载完成后初始化统计
    document.addEventListener('DOMContentLoaded', function() {
        updateStats();
        
        // 每30秒更新一次统计
        setInterval(updateStats, 30000);
    });